# coding: utf-8

import sip
import config
import app.tools as tool
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt, SIGNAL
from app.tools.dialog import Dialog
from app.ui.icon import Icon
from abc import ABCMeta, abstractmethod
from app.ui.tab.tab_page_base import TabPageBase


class TabPageAbstract(TabPageBase):

    __metaclass__ = ABCMeta

    def __init__(self, tab, item, factory, name):
        super(TabPageAbstract, self).__init__(tab, name)
        self.tab = tab
        self.item = item
        self.name = name
        self.factory = factory
        self.icon = Icon()
        self._init_common()

    def _init_common(self):
        self.tab_widget_page = self.get_instance()

        self.vertical_box_layout = QtGui.QVBoxLayout(self.tab_widget_page)
        self.vertical_box_layout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)

        self.one_horizontal_box_layout = QtGui.QHBoxLayout()
        self.one_horizontal_box_layout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)

        self.key_label = QtGui.QLabel(self.tab_widget_page)
        self.key_label.setScaledContents(True)
        self.key_label.setObjectName(tool._from_utf8("key_label"))
        self.one_horizontal_box_layout.addWidget(self.key_label)

        self.key_text = QtGui.QLineEdit(self.tab_widget_page)
        self.key_text.setEnabled(False)
        self.key_text.setObjectName(tool._from_utf8("key_text"))
        # metrics = QtGui.QFontMetrics(self.key_text.font())
        # self.key_text.setMaximumWidth(metrics.maxWidth())
        self.one_horizontal_box_layout.addWidget(self.key_text)


        one_spacer_item = QtGui.QSpacerItem(100, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.one_horizontal_box_layout.addItem(one_spacer_item)

        self.ttl_label = QtGui.QLabel(self.tab_widget_page)
        self.ttl_label.setScaledContents(True)
        self.ttl_label.setObjectName(tool._from_utf8("ttl_label"))
        self.ttl_label.setText(tool._from_utf8('TTL:'))
        self.one_horizontal_box_layout.addWidget(self.ttl_label)

        self.ttl_text = QtGui.QLabel(self.tab_widget_page)
        self.ttl_text.setObjectName(tool._from_utf8("ttl_value"))
        self.one_horizontal_box_layout.addWidget(self.ttl_text)

        self.key_ttl_button = QtGui.QPushButton(self.tab_widget_page)
        self.key_ttl_button.setIcon(self.icon.get(config.ICON_TTL))
        self.key_ttl_button.setObjectName(tool._from_utf8("key_ttl_button"))
        self.key_ttl_button.setText(tool._from_utf8('TTL'))
        self.key_ttl_button.clicked.connect(self.event_ttl_clicked)
        self.one_horizontal_box_layout.addWidget(self.key_ttl_button)

        self.key_delete_button = QtGui.QPushButton(self.tab_widget_page)
        self.key_delete_button.setIcon(self.icon.get(config.ICON_DEL))
        self.key_delete_button.setObjectName(tool._from_utf8("key_delete_button"))
        self.key_delete_button.setText(tool._from_utf8('Delete'))
        self.key_delete_button.clicked.connect(self.event_delete_clicked)
        self.one_horizontal_box_layout.addWidget(self.key_delete_button)

        self.key_save_button = QtGui.QPushButton(self.tab_widget_page)
        self.key_save_button.setIcon(self.icon.get(config.ICON_EDIT_DB))
        self.key_save_button.setObjectName(tool._from_utf8("key_save_button"))
        self.key_save_button.setText(tool._from_utf8('Save'))
        self.key_save_button.clicked.connect(self.event_save_clicked)
        self.one_horizontal_box_layout.addWidget(self.key_save_button)
        self.vertical_box_layout.addLayout(self.one_horizontal_box_layout)
        self.render()
        self.timer_start()

    def get_combo_box(self, parent=None):
        value_format_select = QtGui.QComboBox(parent)
        value_format_select.setObjectName(tool._from_utf8("value_format_select"))
        value_format_select.addItem(tool._from_utf8("Text"))
        value_format_select.addItem(tool._from_utf8("Json"))
        self.tab_widget_page.connect(value_format_select, SIGNAL('currentIndexChanged(int)'), self.event_format_changed)
        return value_format_select

    def add_layout(self, layout):
        self.vertical_box_layout.addLayout(layout)

    def set_stretch(self, index, i):
        self.vertical_box_layout.setStretch(index, i)

    def timer_key(self):
        ttl = self.factory.ttl(self.name)
        if ttl == -2:
            self.timer_stop()
            self.tab_widget_page.close()
            index = self.tab.index(self.tab_widget_page)
            if index > -1:
                self.tab.close_tab(index)
            return self.item.remove()
        self.ttl_text.setText(tool._from_utf8(str(ttl)))

    def timer_start(self):
        self._timer = QtCore.QTimer(self.tab_widget_page)
        self.ttl_text.setText(tool._from_utf8(str(self.factory.ttl(self.name))))
        self._timer.timeout.connect(self.timer_key)
        self._timer.start(1000)

    def timer_stop(self):
        if hasattr(self, '_timer') and self._timer:
            self._timer.stop()
            del self._timer

    def render(self):
        self.key_label.setText(tool._from_utf8('%s:' % self.factory.type(self.name).upper()))
        self.key_text.setText(tool._from_utf8(self.name))
        self.ttl_text.setText(tool._from_utf8(str(self.factory.ttl(self.name))))

    @abstractmethod
    def event_save_clicked(self):
        pass

    @abstractmethod
    def event_format_changed(self, index):
        pass

    def event_ttl_clicked(self):
        ttl = self.factory.ttl(self.name)
        value, ok = Dialog.input_int(self.tab_widget_page, 'setting ttl', 'input ttl value(unit:second):', value=ttl, min=-2)
        if ok is False:
            return
        if ttl == value:
            return
        self.factory.persist(self.name) if value == -1 else self.factory.expire(self.name, value)
        self.ttl_text.setText(tool._from_utf8(str(value)))

    def event_delete_clicked(self):
        try:
            self.factory.delete(self.name)
        except Exception as e:
            print(e)
        else:
            self.close()
            self.item.parent().removeChild(self.item)

    def close(self):
        self.timer_stop()
        tab_widget = self.tab_widget_page.parent()
        tab_widget.removeWidget(self.tab_widget_page)
        self.tab_widget_page.close()